let _Vue = null
export default class VueRouter {
	static install (vue) {
		if (VueRouter.install.installed) {
			return
		}

		VueRouter.install.installed = true
		_Vue = vue
		_Vue.mixin({
			beforeCreate() {
				if (this.$options.router) {
					_Vue.prototype.$router = this.$options.router
					this.$options.router.init()
				}
			}
		})
	}

	constructor (options) {
		this.options = options
		this.routeMap = {}
		this.data = _Vue.observable({
			current: window.location.pathname
		})
	}

	init () {
		this.createRouteMap()
        this.initComponent(_Vue)
        this.initEvent()
	}

	createRouteMap () {
		this.options.routes.forEach((item) => {
			this.routeMap[item.path] = item.component
		})
	}

	initComponent (Vue) {
		Vue.component('router-link', {
			props: {
				to: String
			},
			render (h) {
				return h('a', {
					attrs: {
						href: '#/' + this.to
					},
					// on: {
					// 	click: this.clickHander
					// }
				}, [this.$slots.default])
			}
			// ,
			// methods: {
			// 	clickHander (e) {
			// 		history.pushState({}, null, this.to)
			// 		this.$router.data.current = this.to
			// 		e.preventDefault()
			// 	}
			// }
		})

		const self = this
        Vue.component("router-view",{
            render(h){
                // self.data.current
                const cm = self.routeMap[self.data.current]
                return h(cm)
            }
        })
	}

	initEvent () {
		// window.addEventListener('popstate', () => {
		// 	this.data.current = window.location.pathname
		// })
		window.addEventListener('hashchange', () => {
			this.data.current = window.location.hash.slice('1') || '/' 
		})
	}
}